package net.alpcontrol.bi.colligation.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import net.alpcontrol.bi.bootstrap.utils.ExcelUtils;
import net.alpcontrol.bi.colligation.entity.PjProjectTarget;
import net.alpcontrol.bi.colligation.mapper.CompositeViewMapper;
import net.alpcontrol.bi.colligation.mapper.PjProjectTargetMapper;
import net.alpcontrol.bi.colligation.service.IPjProjectTargetService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 丛庆
 * @since 2020-09-10
 */
@Service
@Transactional
public class PjProjectTargetServiceImpl extends ServiceImpl<PjProjectTargetMapper, PjProjectTarget> implements IPjProjectTargetService {

    @Autowired
    private PjProjectTargetMapper pjProjectTargetMapper;

    /**
      *  分页查询
      * @param bootStrapTable
      * @param pjProjectTarget
      * @return
      */
    @Override
    public IPage<PjProjectTarget> selectPage(Page<PjProjectTarget> page) {
        return pjProjectTargetMapper.selectPage(page,null);
    }

    /**
     * 根据年份和公司查询项目的目标值
     *
     * @param year
     * @param companyId
     * @return
     */
    @Override
    public List<Map> getPjTargetByYearAndCo(String year, String companyId) {
        Map<String,String> param = new HashMap<>();
        param.put("year",year);
        param.put("companyId",companyId);
        List<PjProjectTarget> pjTargetList = pjProjectTargetMapper.getPjTargetByYearAndCo(param);
        List<Map> resultList = new ArrayList<>();
        Map dqxmsyMap=new HashMap();
        dqxmsyMap.put("kpiName","项目抄表值");
        Map dqsbztsMap=new HashMap();
        dqsbztsMap.put("kpiName","项目当前运行台套");
        Map pjjdlMap=new HashMap();
        pjjdlMap.put("kpiName","项目节电率");
        Map pureProfitMap=new HashMap();
        pureProfitMap.put("kpiName","项目净利润");
        Map salesMap=new HashMap();
        salesMap.put("kpiName","项目销售收入");
        Map costMap=new HashMap();
        costMap.put("kpiName","项目主营成本");
        Map expenseMap=new HashMap();
        expenseMap.put("kpiName","项目直接费用");
        for (PjProjectTarget p:pjTargetList) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String month = sdf.format(p.getDateMonth()).substring(5,7);
            dqxmsyMap.put(month,p.getDqxmsyTarget()!=null?p.getDqxmsyTarget():0);
            dqsbztsMap.put(month,p.getDqsbztsTarget()!=null?p.getDqsbztsTarget():0);
            pjjdlMap.put(month,p.getPjjdlTarget()!=null?p.getPjjdlTarget():0);
            pureProfitMap.put(month,p.getPureProfitTarget()!=null?p.getPureProfitTarget():0);
            salesMap.put(month,p.getSalesTarget()!=null?p.getSalesTarget():0);
            costMap.put(month,p.getCostTarget()!=null?p.getCostTarget():0);
            expenseMap.put(month,p.getExpenseTarget()!=null?p.getExpenseTarget():0);

        }
        resultList.add(dqxmsyMap);
        resultList.add(dqsbztsMap);
        resultList.add(pjjdlMap);
        resultList.add(pureProfitMap);
        resultList.add(salesMap);
        resultList.add(costMap);
        resultList.add(expenseMap);
        return resultList;
    }

    /**
     * 导入年度预算值
     *
     * @param file
     * @param year
     * @param companyId
     * @return
     */
    @Override
    public void importTargets(MultipartFile file, String year, String companyId) throws Exception {
        // 没有使用实体类注解的形式，这里用的Map
        ImportParams params = new ImportParams();
        params.setTitleRows(1);//标题的行数
        params.setHeadRows(1);//表头的行数
        params.setReadRows(6);//读取的行数（从0开始，共读取7行，则设为6）
        List<Map<String,Object>> list = ExcelImportUtil.importExcel(
                file.getInputStream(),
                Map.class,
                params
        );
        PjProjectTarget pt = new PjProjectTarget();
        pt.setPureProfitTarget(0f);
        pt.setSalesTarget(0f);
        pt.setCostTarget(0f);
        pt.setExpenseTarget(0f);
        pt.setDqxmsyTarget(0f);
        pt.setDqsbztsTarget(0f);
        pt.setPjjdlTarget(0f);
        for (Map<String, Object> map : list) {
            String kpi = map.get("指标").toString();
            pt.setCompanyId(companyId);
            for(String key:map.keySet()){
                if(key.endsWith("月")) {
                    Integer month = Integer.parseInt(key.split("月")[0]);
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    Date monthDate = sdf.parse(year + "-" + (month > 10 ? month : "" + month) + "-01");
                    pt.setDateMonth(monthDate);
                    switch (kpi){
                        case "项目净利润":
                            pt.setPureProfitTarget(map.get(key)==null?0f:Float.parseFloat(map.get(key).toString()));
                            break;
                        case "项目销售收入":
                            pt.setSalesTarget(map.get(key)==null?0f:Float.parseFloat(map.get(key).toString()));
                            break;
                        case "项目主营成本":
                            pt.setCostTarget(map.get(key)==null?0f:Float.parseFloat(map.get(key).toString()));
                            break;
                        case "项目直接费用":
                            pt.setExpenseTarget(map.get(key)==null?0f:Float.parseFloat(map.get(key).toString()));
                            break;
                        case "项目抄表值":
                            pt.setDqxmsyTarget(map.get(key)==null?0f:Float.parseFloat(map.get(key).toString()));
                            break;
                        case "项目当前运行台套":
                            pt.setDqsbztsTarget(map.get(key)==null?0f:Float.parseFloat(map.get(key).toString()));
                            break;
                        default://项目节电率
                            pt.setPjjdlTarget(map.get(key)==null?0f:Float.parseFloat(map.get(key).toString()));
                            break;
                    }
                    pjProjectTargetMapper.importTargets(pt);
                }
            }

        }
    }

    /**
     * 导出预算excel
     *
     * @param servletResponse
     * @param year
     * @param companyId
     */
    @Override
    public void exportTarget(HttpServletResponse servletResponse, String year, String companyId) {
        TemplateExportParams params = new TemplateExportParams(ExcelUtils.convertTemplatePath("excelTemplates/projectTargetModel.xlsx"), true);
        // 数据模板
        Map<String, Object> data = new HashMap<String, Object>();
        // 填充月份
        data.put("year",year);
        //支出情况
        List<Map> targetList = getPjTargetByYearAndCo(year,companyId);
        data.put("targetList",targetList);
        try {
            ExcelUtils.exportExcelByTemplate(params,data,year+"年项目目标值报表.xlsx",servletResponse);
            System.out.println("导出成功");
        } catch (Exception e) {
            System.out.println("导出Excel，失败:" + e);
        }
    }


}
